package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String cacheKey = CACHE_SHOP_KEY + "type";
        // 查询缓存
        List<String> shopTypeJsonList = stringRedisTemplate.opsForList().range(cacheKey, 0, -1);
        log.info("直接返回缓存中的店铺类型数据: {}", shopTypeJsonList);

        // 判断缓存是否存在
        if (shopTypeJsonList != null && !shopTypeJsonList.isEmpty()) {
            // 将JSON字符串列表转换为ShopType对象列表
            List<ShopType> shopTypes = shopTypeJsonList.stream()
                    .map(json -> JSONUtil.toBean(json, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(shopTypes);
        }

        // 缓存不存在，查询数据库
        LambdaQueryWrapper<ShopType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(ShopType::getSort);
        List<ShopType> shopTypes = list(queryWrapper);
        log.info("查询数据库中的店铺类型数据: {}", shopTypes);

        // 将查询结果存入缓存（以List类型存储）
        // 先将每个ShopType对象转换为JSON字符串
        List<String> jsonList = shopTypes.stream()
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList());

        // 批量添加到Redis的List中（直接传入jsonList，无需再次序列化）
        stringRedisTemplate.opsForList().rightPushAll(cacheKey, jsonList);
        stringRedisTemplate.expire(cacheKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        log.info("将店铺类型数据存入缓存: {}", shopTypes);


        // 返回结果
        return Result.ok(shopTypes);
    }
}